package com.sbp.message.service.cs;

import com.dap.utils.IdGenerator;
import com.sbp.message.entity.TopicRegistry;
import com.sbp.message.dao.IDaoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TopicRegistryCSImpl {
    private static final Logger logger = LoggerFactory.getLogger(TopicRegistryCSImpl.class);

    @Autowired
    private IDaoService daoService;


    private int insertTopicRegistry(TopicRegistry topicRegistry) {
        Date now = new Date();
        topicRegistry.setCreateTime(now);
        topicRegistry.setUpdateTime(now);
        return daoService.insert(topicRegistry);
    }
    private int insertFirstTopicRegistry(String destination, String appName) {
        TopicRegistry topicRegistry = new TopicRegistry();
        topicRegistry.setId(String.valueOf(IdGenerator.generateId()));
        topicRegistry.setDestination(destination);
        topicRegistry.setConsumers(1);
        topicRegistry.setConsumersDescribe("," + appName + ",");

        return insertTopicRegistry(topicRegistry);
    }
    private int addConsumerByDestination(String destination, String appName) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("destination", destination);
        paramMap.put("newConsumersDescribe", appName);
        paramMap.put("updateTime", new Date());
        return daoService.update(TopicRegistry.class, "addConsumerByDestination", paramMap);
    }
    public int updateTopicRegistry(String topic, String appName) {
        try {
            return insertFirstTopicRegistry(topic, appName);
        } catch (DuplicateKeyException e) {
            return addConsumerByDestination(topic, appName);
        }
    }


    public TopicRegistry selectTopicListByDestination(String destination) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("destination", destination);
        return daoService.selectOne(TopicRegistry.class, "selectTopicListByDestination", paramMap);
    }

}
